import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cwhisky/bean/mall_home_entity.dart';
import 'package:flutter_cwhisky/common/style/colors.dart';
import 'package:flutter_cwhisky/common/style/dimens.dart';
import 'package:flutter_cwhisky/common/style/images.dart';
import 'package:flutter_cwhisky/component/business/good/good_view.dart';
import 'package:flutter_cwhisky/component/business/home_member_good.dart';
import 'package:flutter_cwhisky/component/business/home_prefecture_style1/home_prefecture_style1_view.dart';
import 'package:flutter_cwhisky/component/business/homt_adv.dart';
import 'package:flutter_cwhisky/component/business/mall_good.dart';
import 'package:flutter_cwhisky/component/business/memer_good.dart';
import 'package:flutter_cwhisky/component/business/prefecture/multiple_prefecture_view.dart';
import 'package:flutter_cwhisky/component/ink/ink_well_custom2.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:marquee/marquee.dart';

import '../../../../component/base/base_state_less_view.dart';
import '../../../../component/business/prefecture/single_prefecture_view.dart';
import '../../../../component/common_decoration.dart';
import '../../../../component/delegate/ceiling_header_delegate.dart';
import '../../../../component/image_view.dart';
import '../../../../component/ink/ink_well_custom.dart';
import '../../../../component/text_view.dart';
import 'choice_logic.dart';

class ChoicePage extends BaseStateLessView<ChoiceLogic> {
  const ChoicePage({super.key});

  @override
  Widget buildContent(BuildContext context) {
    var w = MediaQuery.of(context).size.width;
    var h = MediaQuery.of(context).size.height;
    return NestedScrollView(
        physics: BouncingScrollPhysics(),
        controller: controller.scrollController,
        headerSliverBuilder: (context, innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(
              child: _banner(),
            ),
            SliverToBoxAdapter(
              child: _buildAnnouncement(),
            ),
            SliverToBoxAdapter(
              child: _topMenu(),
            ),
            SliverToBoxAdapter(
              child: HomeAdv(
                adv: controller.adv1,
                aspectRatio: 345 / 60,
              ),
            ),
            SliverToBoxAdapter(
              child: HomeMemberGood(memberArea: controller.memberArea),
            ),
            SliverToBoxAdapter(
              child: HomePrefectureStyle1Component(prefecture: controller.prefecture),
            ),
            SliverToBoxAdapter(child: _buildOtherPrefecture()),
            SliverToBoxAdapter(
              child: Container(
                margin: EdgeInsets.only(bottom: 6.r),
                child: HomeAdv(
                  adv: controller.adv2,
                  aspectRatio: 345 / 80,
                ),
              ),
            ),
            _buildTabBar(),
          ];
        },
        body: _buildBody());
  }

  _buildBody2() {
    return Container(
      height: 1200,
      color: AppColors.blue,
      margin: EdgeInsets.only(top: 12.r, left: Dimens.horizontalMargin, right: Dimens.horizontalMargin),
    );
  }

  _buildBody() {
    return SingleChildScrollView(
      child: GetBuilder<ChoiceLogic>(
        id: 'recommendGoodList',
        builder: (logic) => Container(
            margin: EdgeInsets.only(top: 12.r, left: Dimens.horizontalMargin, right: Dimens.horizontalMargin),
            child: StaggeredGrid.count(
              crossAxisCount: 2,
              mainAxisSpacing: 9.r,
              crossAxisSpacing: 9.r,
              children: _buildListItem(),
            )),
      ),
    );
  }

  _bannerLabel(String icon, String label) {
    return Flexible(
        child: Container(
      alignment: Alignment.center,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          ImageView(
            url: icon,
            height: 14.h,
          ),
          Padding(
            padding: EdgeInsets.only(
              left: 4.w,
            ),
            child: TextView(
              text: label,
              fontSize: 12.sp,
              fontColor: AppColors.color99,
            ),
          )
        ],
      ),
    ));
  }

  /// 轮播图
  Widget _banner() {
    return Container(
      margin: EdgeInsets.only(left: Dimens.horizontalMargin, right: Dimens.horizontalMargin),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.r)),
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: 345 / 148,
            child: Swiper(
              itemCount: controller.banners.length,
              pagination: SwiperPagination(
                  builder: DotSwiperPaginationBuilder(
                      size: 4.r, activeSize: 4.r, color: AppColors.color99, activeColor: AppColors.white)),
              autoplay: true,
              itemBuilder: (context, index) {
                return ImageView(
                  url: controller.banners[index].image ?? '',
                  borderRadius: BorderRadius.only(topRight: Radius.circular(4.r), topLeft: Radius.circular(4.r)),
                  fit: BoxFit.fill,
                );
              },
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: AppColors.white,
              borderRadius: BorderRadius.only(bottomRight: Radius.circular(4.r), bottomLeft: Radius.circular(4.r)),
            ),
            padding: EdgeInsets.symmetric(vertical: 8.h),
            child: Row(
              children: [
                _bannerLabel('assets/images/icon_banner1.png', '正品行货'),
                _bannerLabel('assets/images/icon_banner2.png', '24小时发货'),
                _bannerLabel('assets/images/icon_banner3.png', '售后无忧'),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _buildAnnouncement() {
    return controller.announcement == null
        ? const SizedBox()
        : Container(
            height: 34.h,
            padding: EdgeInsets.only(left: 15.r),
            margin: EdgeInsets.only(top: 8.r, left: Dimens.horizontalMargin, right: Dimens.horizontalMargin),
            decoration: commDecoration(radius: 17.r),
            child: Row(
              children: [
                ImageView(
                  url: AppImages.iconAnnouncement,
                  width: 15.w,
                  height: 12.h,
                ),
                Padding(
                  padding: EdgeInsets.only(left: 4.r),
                  child: TextView(
                    text: '公告',
                    fontColor: AppColors.colorF46309,
                    fontSize: 13.sp,
                  ),
                ),
                Expanded(
                    child: Container(
                  margin: EdgeInsets.only(left: 4.r),
                  child: Marquee(
                    style: TextStyle(fontSize: 13.sp, color: AppColors.color33),
                    text: controller.announcement?.title ?? '暂无公告',
                    blankSpace: 80.0,
                  ),
                ))
              ],
            ),
          );
  }

  Widget _topMenu() {
    List<Widget> menus = controller.topMenu
        .map((e) => InkWellCustom(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ImageView(
                    url: e.image ?? '',
                    width: 36.r,
                    height: 36.r,
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 3.r),
                    child: TextView(
                      text: e.name ?? '',
                      fontSize: 12.sp,
                      fontColor: AppColors.color66,
                    ),
                  )
                ],
              ),
              onTap: () {},
            ))
        .toList();

    return controller.topMenu.isEmpty
        ? const SizedBox()
        : Container(
            margin: EdgeInsets.only(top: 16.r, left: 26.r, right: 26.r),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: menus,
            ),
          );
  }

  Widget _buildOtherPrefecture() {
    if (controller.otherPrefecture != null && controller.otherPrefecture!.isNotEmpty) {
      List<Widget> list = controller.otherPrefecture!.map((e) {
        if (e.children!.length == 1) {
          return SinglePrefectureComponent(
            prefecture: e,
          );
        } else {
          return MultiplePrefectureComponent(prefecture: e);
        }
      }).toList();
      return Column(
        children: list,
      );
    } else {
      return const SizedBox();
    }
  }

  Widget _buildTabBar() {
    if (controller.recommend == null) {
      return const SliverToBoxAdapter(
        child: SizedBox(),
      );
    }

    return SliverPersistentHeader(
      // SliverPersistentHeader：吸顶效果
      pinned: true,
      floating: true,
      delegate: CeilingHeaderDelegate(
          child: GetBuilder<ChoiceLogic>(
        id: 'recommendList',
        builder: (logic) {
          return Container(
            margin: EdgeInsets.only(top: 6.r, bottom: 6.r),
            color: AppColors.transparent,
            child: ListView.builder(
                itemCount: controller.recommend!.length,
                scrollDirection: Axis.horizontal,
                itemBuilder: (context, index) {
                  var item = controller.recommend![index];
                  var select = controller.recommendIndex == index;
                  return InkWellCustom(
                    onTap: () {
                      controller.clickRecommend(index);
                    },
                    child: Container(
                      padding: EdgeInsets.only(top: 4.r),
                      width: 84.r,
                      child: Row(
                        children: [
                          Expanded(
                              child: Column(
                            children: [
                              TextView(
                                text: item.name ?? '',
                                fontSize: 15.sp,
                                fontWeight: FontWeight.w500,
                                fontColor: select ? AppColors.colorF46309 : AppColors.color332B29,
                              ),
                              Container(
                                margin: EdgeInsets.only(top: 4.r),
                                decoration: BoxDecoration(
                                    color: select ? AppColors.colorF46309 : AppColors.transparent,
                                    borderRadius: BorderRadius.circular(10.r)),
                                padding: EdgeInsets.symmetric(vertical: 2.r, horizontal: 4.r),
                                child: TextView(
                                  text: item.subName ?? '',
                                  fontColor: select ? AppColors.white : AppColors.colorB2,
                                  fontSize: 10.sp,
                                ),
                              ),
                              // Container(
                              //   width: 12.r,
                              //   height: 2.r,
                              //   decoration: BoxDecoration(color: AppColors.colorF46309, borderRadius: BorderRadius.circular(2)),
                              // )
                            ],
                          )),
                          Container(
                            color: const Color(0xffDEDEDE),
                            width: 0.5.r,
                            height: 24.r,
                          )
                        ],
                      ),
                    ),
                  );
                }),
          );
        },
      )), // 不能直接实现，代理为抽象类；所以继承此代理
    );
  }

  List<Widget> _buildListItem() {
    if (controller.goodList == null) return [];
    var list = controller.goodList!
        .map((e) => StaggeredGridTile.count(
            crossAxisCellCount: 1,
            mainAxisCellCount: 1.9,
            child: Container(
              alignment: Alignment.center,
              decoration: BoxDecoration(color: AppColors.white, borderRadius: BorderRadius.circular(10.r)),
              height: 305.r,
              child: GoodComponent(good: e),
            )))
        .toList();

    List<StaggeredGridTile> newList =[];
    newList.add(StaggeredGridTile.count(
      crossAxisCellCount: 1,
      mainAxisCellCount: 1.65,
      child: SizedBox(
        height: 266.r,
        child: ImageView(
          url: controller.adv3!.image ?? '',
          fit: BoxFit.fill,
        ),
      ),
    ));
    newList.addAll(list);
    return newList;
  }
}
